package com.example.designpatterns.composite;

import java.util.ArrayList;
import java.util.List;

// 容器组件：表示树形结构中的容器节点
public class Composite extends Component {
    private List<Component> children = new ArrayList<>();

    public Composite(String name) {
        super(name);
    }

    @Override
    public void display(int depth) {
        // 兼容 Java 8 及以上版本的写法
        StringBuilder dashes = new StringBuilder();
        for (int i = 0; i < depth; i++) {
            dashes.append("-");
        }
        System.out.println(dashes.toString() + name);

        for (Component child : children) {
            child.display(depth + 2);
        }
    }

    @Override
    public void add(Component component) {
        children.add(component);
    }

    @Override
    public void remove(Component component) {
        children.remove(component);
    }

    @Override
    public Component getChild(int index) {
        return children.get(index);
    }
}
